package cn.lg.soar.generator.controller;

import cn.lg.soar.common.data.dict.DictItem;
import cn.lg.soar.common.model.HttpResult;
import cn.lg.soar.common.model.PageQuery;
import cn.lg.soar.common.model.PageResult;
import cn.lg.soar.generator.model.GenConfig;
import cn.lg.soar.generator.service.impl.TableService;
import cn.lg.soar.generator.util.Utils;
import freemarker.template.TemplateException;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@CrossOrigin
@Tag(name = "根据表格生成代码")
@RestController
@RequestMapping(value = "generator", name = "根据表格生成代码")
public class TableController {

    @Autowired
    private TableService service;

    @GetMapping(value = "dbList", name = "获取所有数据源")
    public HttpResult<List<DictItem<String>>> dbList(){
        return HttpResult.data(service.dbList());
    }

    @GetMapping(value = "tableList", name = "获取所有表格")
    public HttpResult<PageResult<Map<String, Object>>> getTableList(
            @RequestParam(name = "dataSourceId", required = false) String dataSourceId,
            @RequestParam(name = "TABLE_NAME", required = false) String TABLE_NAME,
            PageQuery pageQuery
    ){
        return HttpResult.data(
                service.getTableList(dataSourceId, TABLE_NAME, pageQuery)
        );
    }

    @GetMapping(value = "tableInfo", name = "获取表格信息生成配置")
    public HttpResult<GenConfig> getTableInfo(
            @RequestParam(name = "dataSourceId", required = false) String dataSourceId,
            @RequestParam(name = "tableName") String tableName
    ){
        return HttpResult.data(
                service.genConfig(dataSourceId, tableName)
        );
    }

    @PostMapping(value = "parseTableInfo", name = "解析表格信息生成配置")
    public HttpResult<GenConfig> parseTableInfo(@RequestBody String ddl){
        return HttpResult.data(
                Utils.genConfig(
                        Utils.parseTableInfo(ddl)
                )
        );
    }

    @PostMapping(value = "generate", name = "生成代码")
    public HttpResult<Void> generate(@RequestBody GenConfig config) throws TemplateException, IOException {
        Utils.generate(config);
        return HttpResult.success();
    }

}
